package com.mimc.service;

import cn.hutool.core.date.DateUtil;
import com.jfinal.upload.UploadFile;
import com.mimc.framework.config.MinIoClientConfig;
import com.mimc.framework.manager.vo.MinioConf;
import com.mimc.framework.utils.ShUtils;
import io.jboot.Jboot;
import io.jboot.aop.annotation.Bean;
import io.minio.*;
import io.minio.errors.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Date;

@Slf4j
@Bean
public class ShMinioService {
    public void makeBucket(String bucketName) {
        MinioClient instance= ShUtils.getMinio();
        try {
            boolean isExist = instance.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
            if (!isExist) {
                instance.makeBucket(MakeBucketArgs.builder()
                        .bucket(bucketName)
                        .build());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 文件上传
     * @bucketName bucket名称
     * @path 路径
     * @param file 文件
     * @return Boolean
     */
    public String upload(String bucketName, String path, UploadFile file) {
        MinioClient instance= ShUtils.getMinio();
        String originalFilename = file.getOriginalFileName();
        if (StringUtils.isBlank(originalFilename)){
            throw new RuntimeException();
        }
        String fileName = System.currentTimeMillis() + originalFilename.substring(originalFilename.lastIndexOf("."));
        String format = DateUtil.format(new Date(), "yyyyMMdd");
        String objectName = format+ "/" + fileName;
        try {
            InputStream stream = new FileInputStream(file.getFile());
            PutObjectArgs objectArgs = PutObjectArgs.builder().bucket(bucketName).object(path+"/" +objectName)
                    .stream(stream, file.getFile().length(), -1).contentType(file.getContentType()).build();
            //文件名称相同会覆盖
            instance.putObject(objectArgs);
        } catch (Exception e) {
            log.error("上传图片失败,",e);
            return null;
        }
        return objectName;
    }
    /**
     * 文件上传
     * @bucketName bucket名称
     * @path 路径
     * @param file 文件
     * @return Boolean
     */
    public static String upload(String path, UploadFile file) {
        MinioClient instance= ShUtils.getMinio();
        MinioConf minioConf=ShUtils.getMinioConf();
        String originalFilename = file.getOriginalFileName();
        if (StringUtils.isBlank(originalFilename)){
            throw new RuntimeException();
        }
        String fileName = System.currentTimeMillis() + originalFilename.substring(originalFilename.lastIndexOf("."));
        String format = DateUtil.format(new Date(), "yyyyMMdd");
        String objectName = format+ "/" + fileName;
        log.info("bucket:{},objectName:{}",minioConf.getBucket(),objectName);
        try {
            InputStream stream = new FileInputStream(file.getFile());
            PutObjectArgs objectArgs = PutObjectArgs.builder().bucket(minioConf.getBucket()).object(path+"/"+objectName)
                    .stream(stream, file.getFile().length(), -1).contentType(file.getContentType()).build();
            //文件名称相同会覆盖
            instance.putObject(objectArgs);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("上传图片失败,",e);
            return null;
        }
        return objectName;
    }
    public static String uploadAvatar(String objectName, UploadFile file){
        MinioClient instance= ShUtils.getMinio();
        MinioConf minioConf=ShUtils.getMinioConf();
        String originalFilename = file.getOriginalFileName();
        if (StringUtils.isBlank(originalFilename)){
            throw new RuntimeException();
        }
        try {
            InputStream stream = new FileInputStream(file.getFile());
            PutObjectArgs objectArgs = PutObjectArgs.builder().bucket(minioConf.getBucket()).object(objectName)
                    .stream(stream, file.getFile().length(), -1).contentType(file.getContentType()).build();
            //文件名称相同会覆盖
            instance.putObject(objectArgs);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("上传图片失败,",e);
            return null;
        }
        return objectName;
    }
    public static String uploadAvatar(String objectName,byte[] fileByte) {
        MinioClient instance= ShUtils.getMinio();
        MinIoClientConfig minIoClientConfig=Jboot.config(MinIoClientConfig.class);

        try {
            InputStream stream = new ByteArrayInputStream(fileByte);
            PutObjectArgs objectArgs = PutObjectArgs.builder().bucket(minIoClientConfig.getBucketName()).object(objectName)
                    .stream(stream, fileByte.length, -1).contentType("image/png").build();
            //文件名称相同会覆盖
            instance.putObject(objectArgs);
        } catch (Exception e) {
            log.error("上传图片失败,",e);
            return null;
        }
        return objectName;
    }
    /**
     * 文件上传
     * @param path 路径
     * @param name 文件名
     * @param fileByte 文件内容
     * @param contentType
     * @return Boolean
     */
    public static String upload(String path,String name,byte[] fileByte,String contentType) {
        MinioClient instance= ShUtils.getMinio();
        MinIoClientConfig minIoClientConfig=Jboot.config(MinIoClientConfig.class);
        String fileName = System.currentTimeMillis() + name.substring(name.lastIndexOf("."));
        String format = DateUtil.format(new Date(), "yyyyMMdd");
        String objectName = format+ "/" + fileName;
        try {
            InputStream stream = new ByteArrayInputStream(fileByte);
            PutObjectArgs objectArgs = PutObjectArgs.builder().bucket(minIoClientConfig.getBucketName()).object(path+"/" +objectName)
                    .stream(stream, fileByte.length, -1).contentType(contentType).build();
            //文件名称相同会覆盖
            instance.putObject(objectArgs);
        } catch (Exception e) {
            log.error("上传图片失败,",e);
            return null;
        }
        return objectName;
    }


    /**
     * 删除文件
     *
     * @param bucketName
     * @param objectName
     */

    public static void removeObject(String bucketName, String objectName) {
        try {
            MinioClient instance= ShUtils.getMinio();
            instance.removeObject( RemoveObjectArgs.builder().bucket(bucketName).object(objectName).build());
            log.info("删除成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 删除
     * @param bucketName bucket名称
     * @path path
     * @param fileName
     * @return
     * @throws Exception
     */
    public static boolean remove(String bucketName,String path,String fileName){
        try {
            MinioClient instance= ShUtils.getMinio();
            instance.removeObject( RemoveObjectArgs.builder().bucket(bucketName).object(path+fileName).build());
        }catch (Exception e){
            log.error("删除图片失败,",e);
            return false;
        }
        return true;
    }
}
